import ImageOrIcon from '@/components/ImageOrIcon';
import {
  DiscountType,
  getUsableSelectedCouponList,
  getValidDate,
  ProductType,
} from '@/dataTransfer/coupon.js';
import pClose from '@/images/common/close1.png';
import choice from '@/orderSubPack/images/giftCard/choice.png';
import utils from '@/utils/index';
import { dateFormat } from '@/utils/time.js';
import { Button, Image, ScrollView, Text, View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { AtFloatLayout } from 'taro-ui';
import 'taro-ui/dist/style/components/float-layout.scss';
import './index.scss';

const CouponItem = ({
  isAvailable,
  handleSelected,
  item,
  item: {
    type,
    discountAmount,
    minAmount,
    startTime,
    endTime,
    selected,
    merchantName,
    productType,
    sourceType,
    orgName,
    reason,
    categorys = [],
    activityType,

    timeType,
  },
}) => {
  const isShop = type === DiscountType.rebate || type === DiscountType.discount;
  const isRebate = type === DiscountType.rebate || type === DiscountType.rebateT;

  const timeRangeStr = useMemo(() => {
    let formatter = 'yyyy.MM.dd hh:mm';

    if (timeType === 2) {
      formatter = 'yyyy.MM.dd';
    }

    return (
      dateFormat(getValidDate(startTime), formatter) +
      '-' +
      dateFormat(getValidDate(endTime), formatter)
    );
  }, [timeType]);

  return (
    <View className="coupon-item-wrap">
      <View className={classNames('coupon-item', { available: isAvailable })}>
        <View className="left">
          <View
            className={classNames('coupon-price', {
              off: !isRebate,
            })}
          >
            {isRebate ? (
              <>
                <Text className={classNames('unit', { customePageStyle: isAvailable })}>¥</Text>
                <Text className={classNames('price', { customePageStyle: isAvailable })}>
                  {discountAmount}
                </Text>
              </>
            ) : (
              <>
                <Text className={classNames('unit', { customePageStyle: isAvailable })}>
                  {discountAmount}
                </Text>
                <Text className={classNames('price', { customePageStyle: isAvailable })}>折</Text>
              </>
            )}
          </View>
          <View className={classNames('coupon-discount', { available: isAvailable })}>
            {minAmount == 0 ? (
              <View className="min-amount">无门槛</View>
            ) : isRebate ? (
              <View className="min-amount">
                满{minAmount}减{discountAmount}
              </View>
            ) : (
              <View className="min-amount">
                满{minAmount}打{discountAmount}折
              </View>
            )}
          </View>
        </View>
        <View className="middle">
          <View className="info">
            {isShop
              ? (sourceType == 1
                  ? merchantName + (productType === ProductType.all ? '全部' : '部分')
                  : '商城' +
                    (productType === ProductType.all ? '全品类' : categorys.join('、') + '类')) +
                '商品可用'
              : sourceType == 1
              ? orgName + '外卖专享'
              : productType === ProductType.all
              ? '外卖店铺专享'
              : categorys.join('、') + '外卖专享'}
          </View>
          <View className="time">{timeRangeStr}</View>
          {isAvailable && sourceType == 0 && activityType.indexOf('2') == -1 && (
            <View className="attention">此券不可和商家券叠加使用</View>
          )}
        </View>
        {isAvailable ? (
          <View
            className="right"
            onClick={() => {
              handleSelected(item);
            }}
          >
            <ImageOrIcon
              {...{
                className: 'img',

                name: selected === 1 && 'icon_chose',
                size: 36,

                src: choice,
              }}
            />
          </View>
        ) : (
          <View className="right"></View>
        )}
      </View>

      {!isAvailable && (
        <View className="unavailable-message">
          <View className="pre">本单不可用原因：</View>
          <View className="detail">{reason}</View>
        </View>
      )}
    </View>
  );
};

function isSameSelected(ori = [], view = []) {
  const [a, b] = [ori, view].map((item) => {
    return item
      .filter(({ selected }) => {
        return selected === 1;
      })
      .sort(({ couponId, configId }) => {
        return [couponId, configId].join('|');
      })
      .map(({ couponId, configId }) => {
        return [couponId, configId].join('|');
      })
      .join('/');
  });

  return a === b;
}

const CouponSelect = ({
  isOpened,
  handleClose,
  sourceType,
  usableCouponList,
  disabledCouponList,
}) => {
  const inputCouponList = useRef(usableCouponList);
  const [couponType, setCouponType] = useState('available');
  const [isRecommend, setIsRecommend] = useState(true);

  const isAvailable = couponType === 'available';

  const [usableViewCouponList, setUsableViewCouponList] = useState([]);

  useEffect(() => {
    // 初始化一次 inputCouponList
    if (!inputCouponList.current || !inputCouponList.current.length) {
      inputCouponList.current = usableCouponList;
    }

    setIsRecommend(isSameSelected(inputCouponList.current, usableViewCouponList));
  }, [usableCouponList, usableViewCouponList]);

  // 列表有刷新, 就使用原有列表 覆盖界面显示列表
  useEffect(() => {
    setUsableViewCouponList(usableCouponList ?? []);
  }, [usableCouponList]);

  // 如果没有点确定, 则恢复默认状态
  const closeWithReset = (data) => {
    if (!data) {
      setUsableViewCouponList(usableCouponList ?? []);
    }

    handleClose(data);
  };

  // 一个订单中，每个商户至多使用一张优惠券。
  const handleSelected = ({ couponId, configId }) => {
    const temp = usableViewCouponList.map((item) => {
      return {
        ...item,
        selected:
          item.selected === 2 && item.couponId === couponId && item.configId === configId ? 1 : 2,
      };
    });

    setUsableViewCouponList(temp);
  };

  const { selectedCouponList, discountAmount } = getUsableSelectedCouponList(usableViewCouponList);

  return (
    <View className={classNames('couponSelect', { couponSelectH5: process.env.TARO_ENV === 'h5' })}>
      <AtFloatLayout
        isOpened={isOpened}
        onClose={() => {
          closeWithReset();
        }}
        className="coupon-select"
      >
        <View className="header">
          <View className="top">
            <View className="title">{sourceType ? '商家' : '平台'}优惠券</View>
            <Image
              className="close"
              src={pClose}
              onClick={() => {
                closeWithReset();
              }}
            ></Image>
          </View>

          <View className="coupon-tab customePageBackgroundStyle">
            <View
              className={classNames('item', {
                [`active customePageBorderStyle customePageStyle`]: isAvailable,
              })}
              onClick={() => {
                setCouponType('available');
              }}
            >
              <View className="top">可用优惠券({usableViewCouponList?.length ?? 0})</View>
            </View>

            <View
              className={classNames('item', {
                [`active customePageBorderStyle customePageStyle`]: couponType === 'unavailable',
              })}
              onClick={() => {
                setCouponType('unavailable');
              }}
            >
              <View className="top">不可用优惠券({disabledCouponList?.length ?? 0})</View>
            </View>
          </View>

          {isAvailable ? (
            <View className="coupon-select-notice">
              <View className="note">
                {isRecommend ? '已选中推荐优惠，' : ''}使用优惠券 {selectedCouponList?.length ?? 0}{' '}
                张，共抵扣
              </View>
              <View className="price customePageStyle">
                ¥ {parseFloat(discountAmount).toFixed(2)}
              </View>
            </View>
          ) : null}
        </View>
        <View className="coupon-list">
          <ScrollView
            scrollY
            style={{
              height: utils.getSizeByScale(663) + utils.getSizeByScale(isAvailable ? 0 : 63) + 'px',
            }}
          >
            {(isAvailable ? usableViewCouponList : disabledCouponList)?.map((item) => {
              return (
                <CouponItem
                  key={[item.couponId, item.configId].join('')}
                  item={item}
                  handleSelected={handleSelected}
                  isAvailable={isAvailable}
                ></CouponItem>
              );
            })}
          </ScrollView>
        </View>

        <View className="bottom">
          <View
            className="btnBox"
            onClick={() => {
              closeWithReset(usableViewCouponList);
            }}
          >
            <Button className="btn customePageBackgroundStyle">确定</Button>
          </View>
        </View>
      </AtFloatLayout>
    </View>
  );
};
export default CouponSelect;
